#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include "list.h"


#define SING_FILE "sing_list.txt"


int add_sing(Sing *r)
{
	FILE *fp;

	fp = fopen(SING_FILE,"a");	
	if (fp == NULL)
	{
		perror("open sing file");
		return 1;
	}
	fprintf(fp,"%-20s",r->sing_name);
	fprintf(fp, "%-50s\n",r->sing_path);
	if (fp)
		fclose(fp);
	return 0;
}

int add_sing_all(Sing *r)
{
	FILE *fp;

	fp = fopen(SING_FILE,"w");
	if (fp == NULL)
	{
		perror("open sing file");
		return 1;
	}

	while(r != NULL)
	{
		fprintf(fp,"%-20s",r->sing_name);
		fprintf(fp, "%-50s\n",r->sing_path);
		r = r->next;
	}
	if (fp)
		fclose(fp);
	return 0;
}

Sing* read_singlist()
{
	Sing *head,*p,*newNode,*tp;
	FILE *fp;
	fp = fopen (SING_FILE,"r");
	if (fp == NULL)
	{
		perror("open singlist file read");
		return NULL;
	}
	head = (Sing *)malloc(sizeof(Sing));
	if (NULL == head)
	{
		printf("malloc fail\n");
		if(fp) fclose(fp);
		return NULL;
	}
	memset(head,0,sizeof(Sing));
	head->next = NULL;
	p = head;
	while(!feof(fp))
	{
		fscanf(fp,"%20s",p->sing_name);
		fscanf(fp,"%s",p->sing_path);

		newNode = (Sing*)malloc(sizeof(Sing));
		memset(newNode,0,sizeof(Sing));
		p->next = newNode;
		tp = p;
		p = newNode;
	}
	tp->next = NULL;
	free (p); 
	if(fp) fclose(fp);
	return head;
}

int show_sing(Sing *head)
{
	Sing *p;
	int num = 1;
	p = head;
	printf("##########################\n");
	printf("Num    sing_name           sing_path\n");
	while(p->next)
	{	
		printf("%2d.    %-20s%-50s\n",num,p->sing_name,p->sing_path);
		p = p->next;
		num++;
	}
	printf("##########################\n");
	
	return 0;
}

int tianjia_sing()
{
	Sing *p;
	p = (Sing*)malloc(sizeof(Sing));

	printf("请输入歌曲名::\n");
	fgets(p->sing_name,19,stdin);
	printf("请输入歌曲路径:\n");
	gets(p->sing_path,49,stdin);
	if (access(p->sing_path,F_OK) != 0)
	{
	//	printf("%s\n",p->sing_path);
		printf("该文件不存在!\n");
	}
	else
	{
		if (!ismp3(p->sing_path))
			add_sing(p);
		else
		{
		//	printf("%s\n",p->sing_path);
			printf("该文件不是mp3文件!\n");
		}
	}
	free(p);
	

	printf("输入任意指令以继续:\n");
	getchar();

	return 0;

}

int remove_sing()
{
	
	int s,i;    
	Sing *remove_head,*remove_p,*remove_tp;
	remove_head = read_singlist();
	show_sing(remove_head);
	remove_p = remove_tp = remove_head;
	remove_p = remove_p->next;
	printf("请输入要删除的歌曲对应的编号 :\n");	
	scanf("%d",&s);	
	getchar();
	if(s == 1)
	{		
		free(remove_tp);
		remove_head = remove_p;
	}
	else if(s > 1)
	{
		for (i = 2;i < s;i++)
		{
			remove_p = remove_p->next;
			remove_tp = remove_tp->next;
		}
		remove_tp->next = remove_p->next;   //to remove
		free (remove_p);
	}

	add_sing_all(remove_head);
	printf("输入任意指令以继续:\n");
	getchar();

	return 0;
}

int ismp3_n(char *buf)
{
	int i = strlen(buf);
	char s[10];
	strcpy(s,buf+i-5);
	if (!strcmp(s,".mp3\n"))
		return 0;
	else 
		return 1;
}

int ismp3(char *buf)
{
	int i = strlen(buf);
	char s[10];
	strcpy(s,buf+i-4);
	if (!strcmp(s,".mp3"))
		return 0;
	else 
		return 1;
}


